//********************************************************************
//	created:	16:10:2011   20:19
//	filename: 	requestmanager.cpp
//	author:		tiamo
//	purpose:	request manager
//********************************************************************

#include "stdafx.h"
#include "requestmanager.h"

namespace utils
{
	//
	// do request
	//
	void BaseRequest::doRequest()
	{
		for(uint32_t i = 0; i < mMaxRetry; i ++)
		{
			try
			{
				mResult														= -1;
				doRequestImp();
				if(mResult == -1)
					mResult													= 0;

				break;
			}
			catch(std::exception& e)
			{
				LogError(L"BaseRequest(%p:%ls): request(%u) failed(%ls)", this, mRequestName, i, Exception::getMessage(e).c_str());
			}
		}
	}

	//
	// request done
	//
	void BaseRequest::requestDone()
	{
		try
		{
			if(mCallback)
				mCallback(this);
		}
		catch(std::exception& e)
		{
			LogError(L"BaseRequest(%p:%ls): request callback failed(%ls)", this, mRequestName, Exception::getMessage(e).c_str());
		}
	}

	//
	// process pending request
	//
	void RequestManager::processPendingRequest()
	{
		while(1)
		{
			SmartPointer<BaseRequest> theRequest							= popPendingRequest();
			if(!theRequest)
				break;

			theRequest->doRequest();
			pushFinishedRequest(theRequest);
		}
	}

	//
	// process finished request
	//
	void RequestManager::processFinishedRequest()
	{
		while(1)
		{
			SmartPointer<BaseRequest> theRequest							= popFinishedRequest();
			if(!theRequest)
				break;

			theRequest->requestDone();
		}
	}
}
